package network.netty.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import network.netty.Common;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *
 * </p>
 *
 * @author LovelyBigDuck
 * @date 2021/5/29 15:18
 */
public class UdpClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
        // 收到消息执行的逻辑
        byte[] data = Common.getBody(msg);
        String receive = new String(data, StandardCharsets.UTF_8);
        System.out.println(receive);
    }

    // 当channel激活后要执行的方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("向服务端发送数据。。。");
        String send = "曹尼玛";
        ByteBuf byteBufSend = Unpooled.wrappedBuffer(send.getBytes(StandardCharsets.UTF_8));
        ctx.writeAndFlush(new DatagramPacket(byteBufSend, new InetSocketAddress("localhost", 8080)));
        System.out.println("向服务端发送数据成功。。。");
    }
}
